public with sharing class CaptchaController {

  private static string secret = '6LdoYMwSAAAAAFVdvs61KWOiiGZLlcYmD-Vk2mub';

  public string publicKey { get { return '6LdoYMwSAAAAAFYM0Vvm7cVEoJUS2KCDcecIcXeu' ; }}
 
  private static string baseUrl = 'http://www.google.com/recaptcha/api/verify';
 public string challenge {get; set;} { challenge = null; }

 public string response {get; set; }  { response = null; }



 public Boolean correctResponse { get; private set; } { correctResponse = false; }

  

 public PageReference verify() {

   system.debug( 'verify called ');

       // first time thru, this parameter is null, so no request to make yet

   if ( challenge == null || response == null ) {

         system.debug( 'verify called null ');

         return null;

       }

                  

   HttpResponse r = makeRequest(  baseUrl ,

        'privatekey='+ secret +

        '&remoteip=' + remoteHost +

        '&challenge=' + challenge +

            '&response=' + response +

            '&error=incorrect-captcha-sol'

   );

      

       if ( r != null ) {  // is null when test methods run

         correctResponse = ( r.getBody().contains('true') );

       }

       return null; 

 }



 public PageReference reset() {

     challenge = null;

     response = null;

     return null;

 }  



 public static HttpResponse makeRequest(string url, string body)  {

       HttpRequest req = new HttpRequest();  

       HttpResponse response = null;

       req.setEndpoint( url );

       req.setMethod('POST');

       req.setBody ( body);

       try {

         Http http = new Http();

         response = http.send(req);

         System.debug('response: '+ response);

         System.debug('body: '+ response.getBody());

         

       } catch( System.Exception e) {

          System.debug('ERROR: '+ e);

       }

       return response;

     }  

      

 public string remoteHost { get { string ret = '127.0.0.1';

     // also could use x-original-remote-host

     map<string , string> hdrs = ApexPages.currentPage().getHeaders();

     if ( hdrs.get('x-original-remote-addr') != null)

         ret =  hdrs.get('x-original-remote-addr');

     else if ( hdrs.get('X-Salesforce-SIP') != null)

         ret =  hdrs.get('X-Salesforce-SIP');

     return ret;

 } }

      

 public static  testmethod void test_1() {

     CaptchaController re = new CaptchaController ();

     string href = baseUrl ;

     re.challenge = re.response = 'foo';

     string publick = re.publicKey;

     string host = re.remoteHost;

     re.verify();

 }

 public static  testmethod void test_2() {

     CaptchaController re = new CaptchaController ();

     re.verify();

    }


}